using Microsoft.EntityFrameworkCore;
using WeatherMcpServer.Data.Entities;

namespace WeatherMcpServer.Data.Repositories;

/// <summary>
/// EF Core 实现：预警记录仓储。
/// </summary>
public class EfWeatherAlertRepository : IWeatherAlertRepository
{
    private readonly WeatherDbContext _db;

    public EfWeatherAlertRepository(WeatherDbContext db)
    {
        _db = db;
    }

    public async Task<WeatherAlert> AddAsync(WeatherAlert alert, CancellationToken ct = default)
    {
        await _db.WeatherAlerts.AddAsync(alert, ct);
        return alert;
    }

    public Task<WeatherAlert?> GetByIdAsync(long id, CancellationToken ct = default)
        => _db.WeatherAlerts.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id, ct);

    public async Task<IReadOnlyList<WeatherAlert>> QueryAsync(
        WeatherType? type = null,
        AlertStatus? status = null,
        string? regionCode = null,
        DateTime? fromUtc = null,
        DateTime? toUtc = null,
        int skip = 0,
        int take = 50,
        CancellationToken ct = default)
    {
        var q = _db.WeatherAlerts.AsNoTracking().AsQueryable();
        if (type.HasValue) q = q.Where(x => x.Type == type.Value);
        if (status.HasValue) q = q.Where(x => x.Status == status.Value);
        if (!string.IsNullOrWhiteSpace(regionCode)) q = q.Where(x => x.RegionCode == regionCode);
        if (fromUtc.HasValue) q = q.Where(x => x.CreatedAt >= fromUtc.Value);
        if (toUtc.HasValue) q = q.Where(x => x.CreatedAt <= toUtc.Value);
        return await q.OrderByDescending(x => x.CreatedAt).Skip(skip).Take(take).ToListAsync(ct);
    }

    public Task<int> SaveChangesAsync(CancellationToken ct = default) => _db.SaveChangesAsync(ct);
}
